package com.virus.mall.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Classname FileUploadUtils
 * @Description 上传文件工具类
 * @Date 2021/4/16 23:53
 * @Created by virus
 */
public class FileUploadUtils {

    private static HashMap<String, Object> map = new HashMap<String, Object>();

    public static Map<String, Object> upload(HttpServletRequest request) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        File repository = (File) request.getServletContext().getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            for (FileItem item : fileItems) {
                if (!item.isFormField()) {
                    processUploadFile(request, item);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return map;
    }

    private static void processUploadFile(HttpServletRequest request, FileItem item) {

        String fieldName = item.getFieldName();
        String fileName = item.getName();
        fileName = UUID.randomUUID() + "-" + fileName;
        StringBuffer relativePath = new StringBuffer("image");
        int hashCode = fileName.hashCode();
        String hexString = Integer.toHexString(hashCode);
        for (char c : hexString.toCharArray()) {
            relativePath.append("/").append(c);
        }
        relativePath.append("/").append(fileName);
        String absolutePath = request.getServletContext().getRealPath(relativePath.toString());
//        String absolutePath = request.getServletContext().getAttribute("outPath") + "/"
//                + request.getServletContext().getAttribute("contextName")
//                + "/" + relativePath.toString();
        File file = new File(absolutePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            item.write(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put(fieldName, relativePath.toString());
    }
}
